import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr'

// SignalR 配置
const SIGNALR_CONFIG = {
  URL: 'http://112.126.93.146:8000/lssueread/hubs/stock',
  RECONNECT_INTERVALS: [0, 2000, 10000, 30000],
  WEBSOCKET_TRANSPORT: 1,
  LONG_POLLING_TRANSPORT: 2
}

// 定义仓库数据类型
export interface WarehouseData {
  storageId: number
  name: string
  quantity: number
}

class SignalRService {
  private connection: HubConnection | null = null
  private listeners: Map<string, Function[]> = new Map()
  private connectionStateListeners: Function[] = []

  // 初始化连接
  async initConnection(url: string = SIGNALR_CONFIG.URL) {
    try {
      this.connection = new HubConnectionBuilder()
        .withUrl(url, {
          skipNegotiation: false,
          transport: SIGNALR_CONFIG.WEBSOCKET_TRANSPORT, // 优先使用 WebSockets
          withCredentials: false // 禁用 credentials 模式
        })
        .withAutomaticReconnect(SIGNALR_CONFIG.RECONNECT_INTERVALS) // 自定义重连策略
        .build()

      // 监听连接状态变化
      this.connection.onclose((error) => {
        console.log('SignalR 连接已关闭:', error)
        this.notifyConnectionStateChange(false)
      })

      this.connection.onreconnecting((error) => {
        console.log('SignalR 正在重连:', error)
        this.notifyConnectionStateChange(false)
      })

      this.connection.onreconnected((connectionId) => {
        console.log('SignalR 重连成功:', connectionId)
        this.notifyConnectionStateChange(true)
      })

      // 启动连接
      await this.connection.start()
      console.log('SignalR 连接已建立')
      this.notifyConnectionStateChange(true)
      return true
    } catch (error) {
      console.error('SignalR 连接失败，尝试使用 Long Polling:', error)
      
      // 如果 WebSockets 失败，尝试 Long Polling
      try {
        this.connection = new HubConnectionBuilder()
          .withUrl(url, {
            skipNegotiation: false,
            transport: SIGNALR_CONFIG.LONG_POLLING_TRANSPORT, // Long Polling
            withCredentials: false
          })
          .withAutomaticReconnect(SIGNALR_CONFIG.RECONNECT_INTERVALS)
          .build()

        // 监听连接状态变化
        this.connection.onclose((error) => {
          console.log('SignalR Long Polling 连接已关闭:', error)
          this.notifyConnectionStateChange(false)
        })

        this.connection.onreconnecting((error) => {
          console.log('SignalR Long Polling 正在重连:', error)
          this.notifyConnectionStateChange(false)
        })

        this.connection.onreconnected((connectionId) => {
          console.log('SignalR Long Polling 重连成功:', connectionId)
          this.notifyConnectionStateChange(true)
        })

        await this.connection.start()
        console.log('SignalR Long Polling 连接已建立')
        this.notifyConnectionStateChange(true)
        return true
      } catch (longPollingError) {
        console.error('SignalR Long Polling 也失败:', longPollingError)
        this.notifyConnectionStateChange(false)
        return false
      }
    }
  }

  // 添加监听器
  on(eventName: string, callback: Function) {
    if (!this.connection) {
      console.error('SignalR 连接未建立')
      return
    }

    if (!this.listeners.has(eventName)) {
      this.listeners.set(eventName, [])
    }
    this.listeners.get(eventName)!.push(callback)

    this.connection.on(eventName, (...args) => {
      this.listeners.get(eventName)?.forEach(cb => cb(...args))
    })
  }

  // 移除监听器
  off(eventName: string, callback?: Function) {
    if (!this.listeners.has(eventName)) return

    if (callback) {
      const callbacks = this.listeners.get(eventName)!
      const index = callbacks.indexOf(callback)
      if (index > -1) {
        callbacks.splice(index, 1)
      }
    } else {
      this.listeners.delete(eventName)
    }

    if (this.connection) {
      this.connection.off(eventName)
    }
  }

  // 调用服务器方法
  async invoke(methodName: string, ...args: any[]) {
    if (!this.connection) {
      throw new Error('SignalR 连接未建立')
    }
    return await this.connection.invoke(methodName, ...args)
  }

  // 停止连接
  async stop() {
    if (this.connection) {
      await this.connection.stop()
      this.connection = null
      this.listeners.clear()
    }
  }

  // 获取连接状态
  get isConnected() {
    return this.connection?.state === 'Connected'
  }

  // 添加连接状态监听器
  onConnectionStateChange(callback: Function) {
    this.connectionStateListeners.push(callback)
  }

  // 通知连接状态变化
  private notifyConnectionStateChange(isConnected: boolean) {
    this.connectionStateListeners.forEach(callback => callback(isConnected))
  }
}

// 创建单例实例
export const signalRService = new SignalRService() 